package com.chenxiao.rediscollection.sign.service.Impl;

import com.chenxiao.rediscollection.sign.constants.RedisConstants;
import com.chenxiao.rediscollection.sign.entity.AjaxResult;
import com.chenxiao.rediscollection.sign.service.UserService;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.transform.Result;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author: CX
 * @Date: Created in  2023/12/15 17:22
 * @version: v1.0
 * @Description: TODO
 **/
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private RedisTemplate<String, Object> stringRedisTemplate;
    @Override
    public AjaxResult sign() {
        //1. 获取登录用户
       // Long userId = UserHolder.getUser().getId();
        Long userId =  100L;
        //2. 获取日期
        LocalDateTime now = LocalDateTime.now();
        //3. 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisConstants.USER_SIGN_KEY + userId + keySuffix;
        //4. 获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //5. 写入redis setbit key offset 1
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth -1, true);
        return new AjaxResult("200","成功");
    }

    @Override
    public AjaxResult signCount() {
        //1. 获取登录用户
       // Long userId = UserHolder.getUser().getId();
        Long userId = 100L;
        //2. 获取日期
        LocalDateTime now = LocalDateTime.now();
        //3. 拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = RedisConstants.USER_SIGN_KEY + userId + keySuffix;
        //4. 获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //5. 获取本月截至今天为止的所有的签到记录，返回的是一个十进制的数字 BITFIELD sign:5:202301 GET u3 0
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        //没有任务签到结果
        if (result == null || result.isEmpty()) {
            return new AjaxResult("200","没有任务签到结果");
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            return new AjaxResult("200","没有任务签到结果");
        }
        //6. 循环遍历
        int count = 0;
        while (true) {
            //6.1 让这个数字与1 做与运算，得到数字的最后一个bit位 判断这个数字是否为0
            if ((num & 1) == 0) {
                //如果为0，签到结束
                break;
            } else {
                count ++;
            }
            num >>>= 1;
        }
        return new AjaxResult("200",count);
    }
}
